/*
 * @Author: 深海有鱼 847094299@qq.com
 * @Date: 2025-04-04 00:01:11
 * @LastEditors: 深海有鱼 847094299@qq.com
 * @LastEditTime: 2025-09-07 00:04:35
 * @FilePath: \pure-admin-thin\src\store\modules\taskConfig.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from "pinia";
import { store } from "../utils";
import {
  getGlobalCountries,
  getServiceIcon,
  getGlobalServiceTypes
} from "@/api/globalConfigApi";
import { sortList } from "@/utils/tools";
export const useTaskConfig = defineStore({
  id: "pure-task-config",
  state: (): any => ({
    countries: [],
    serviceTypes: [],
    statusOptions: {},
    iconList: []
  }),
  getters: {
    getStatusOptions({ statusOptions }) {
      return Object.entries(statusOptions).map(([key, value]) => {
        return { value: key, label: value };
      });
    },
    allCountryList({ countries }) {
      return countries;
    }
  },
  actions: {
    getIcon(code: string | string[]) {
      const list = Array.isArray(code) ? code : [code];
      return this.iconList.find(i => list.includes(i.standardCode))?.url || "";
    },
    mergeAndDeduplicate<T extends object>(
      obj: Record<string, T[]>,
      key?: keyof T
    ): T[] {
      // 检查传入的 obj 是否为非空对象
      if (!obj || typeof obj !== "object") {
        throw new Error("Invalid parameter: obj must be a non-null object");
      }

      // 合并对象中所有的数组
      const mergedArray: T[] = Object.values(obj).reduce<T[]>((acc, cur) => {
        if (Array.isArray(cur)) {
          return acc.concat(cur);
        }
        return acc;
      }, []);

      // 如果没有传入 key，则直接返回合并后的数组
      if (!key) {
        return mergedArray;
      }

      // 使用 Map 以指定 key 去重（如果有重复则保留后面的项）
      const uniqueMap = new Map<T[keyof T], T>();
      mergedArray.forEach(item => {
        uniqueMap.set(item[key], item);
      });

      return Array.from(uniqueMap.values());
    },
    async queryIcons() {
      this.iconList = [];
      this.serviceTypes.forEach(({ standardCode }) => {
        // 获取图标
        getServiceIcon(standardCode).then(({ data }) => {
          // 如果data是blob对象，则将其转换为url
          if (data instanceof Blob) {
            const url = URL.createObjectURL(data);
            this.iconList.push({
              url,
              standardCode
            });
          }
        });
      });
    },
    async getServiceTypes() {
      try {
        const { data } = await getGlobalServiceTypes();
        this.serviceTypes = sortList(data);
      } catch (error) {
        console.log(error);
      }
    },
    async getCountry() {
      try {
        const { data } = await getGlobalCountries();
        this.countries = data;
      } catch (error) {
        console.log(error);
      }
    }
  }
});

export function useTaskConfigHook() {
  return useTaskConfig(store);
}
